#include "Register.h"

#include <QMessageBox>
#include <QSqlError>
#include <QSqlQuery>

#include "DebugTool.h"
#include "ui_Register.h"
// 构造函数
Register::Register(QWidget *parent) : QWidget(parent), ui(new Ui::Register) {
  ui->setupUi(this);
  this->setAttribute (Qt::WA_StyledBackground);
}

// 析构函数
Register::~Register() { delete ui; }

// 点击确定按钮
void Register::on_buttonBox_accepted() {
  int e = 1;
  QString error;

  // 检查用户名是否为空
  if (ui->edt_name->text().trimmed().isEmpty())
    error.append(QString("%1) 用户名不能为空\n").arg(e++));

  // 检查密码两次是否一致
  QString pwd1 = ui->edt_pwd1->text();
  QString pwd2 = ui->edt_pwd2->text();
  if (pwd1 != pwd2) {
    error.append(QString("%1) 密码有误，请重新输入！\n").arg(e++));
    ui->edt_pwd1->clear();
    ui->edt_pwd2->clear();
  }

  if (!error.isEmpty()) {
    QMessageBox::information(this, "错误", error);
    return;
  }

  // 检查是否已经存在该用户
  QString sql =
      QString("select * from user where id = '%1'").arg(ui->edt_name->text());
  QSqlQuery query;
  bool ok = query.exec(sql);
  if (ok == false) cout << query.lastError().text();
  if (query.next()) {
    error.append(QString("%1) 已经存在%2用户，请重新输入\n")
                     .arg(e++)
                     .arg(query.value(0).toString()));
    QMessageBox::information(this, "错误", error);
    ui->edt_name->setFocus();
    return;
  }

  // 无错误，则插入user数据库  默认 最大可借 10 本
  sql = QString("insert into user values(%1,%2,'',0,%3);")
            .arg(ui->edt_name->text())
            .arg(ui->edt_pwd1->text())
            .arg(10);

  ok = query.exec(sql);
  if (ok == false) {
    cout << query.lastError().text();
  } else {
    QMessageBox::information(this, "注册成功", "欢迎使用图书馆管理系统");
    emit login(ui->edt_name->text(),false,0,10);  // 发出登陆成功的信号
    this->close();
  }
}

void Register::on_buttonBox_rejected() { this->close(); }
